//
//  TZUserAccount.swift
//  WeiboWithSwift
//
//  Created by 涂真 on 15/12/20.
//  Copyright © 2015年 涂真. All rights reserved.
//

import UIKit

class TZUserAccount: NSObject,NSCoding {
    
    ///是否登录过的属性
    class var isLogin:Bool{
        get{
            return TZUserAccount.loadAccountInfo() != nil
        }
        
    }
    
    //MARK: - 字典转模型
    //需要转模型的属性
    var access_token:String?
    var expires_in:NSTimeInterval=0{
        didSet{
            erpires_Date = NSDate(timeIntervalSinceNow: expires_in)
        }
        
    }
    var uid:String?
    var erpires_Date:NSDate?
    ///用户头像地址（大图），180×180像素头像
    var avatar_large:String?
    ///用户昵称
    var screen_name:String?
    
    
    ///通过构造方法完成字典转模型
    init(dict:[String:AnyObject]) {
        super.init()
        self.setValuesForKeysWithDictionary(dict)
    }
    
    
    //当字典的key在模型中找不到属性时调用
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    /// 4.打印对象内容
    override var description: String {
        get {
            return "access_token: \(access_token), uid: \(uid), expires_in: \(expires_in), expires_Date: \(erpires_Date)"
        }
    }
    
    
    //MARK: - 归档和反归档
    //归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(erpires_Date, forKey: "erpires_Date")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        
    }
    //解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        erpires_Date = aDecoder.decodeObjectForKey("erpires_Date") as?NSDate
        screen_name = aDecoder.decodeObjectForKey("screen_name") as?String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as?String
    }
    
    
    ///沙盒路径
    static var path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("accountInfo.plist")
    ///存储模型
    func saveAccountInfo(){
        //TODO:打印沙盒路劲
//        print(TZUserAccount.path)
        NSKeyedArchiver.archiveRootObject(self, toFile:TZUserAccount.path)
    }
    ///存储模型的属性
    static var accountInfo:TZUserAccount?
    ///获取模型
    class func loadAccountInfo()->TZUserAccount?{
        //获取账户信息
        if accountInfo == nil{
            //先从沙盒中获取账户信息
            accountInfo = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? TZUserAccount
        }
        
        if accountInfo != nil && accountInfo?.erpires_Date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            //有可用的账户信息
            return accountInfo
        }
        //到这步说明access_token过期，或者沙盒中没有存储账户信息
        return nil
    }
    
    //MARK: - 使用网络工具类加载用户信息
    ///获取用户信息
    func loadUserInfo(finished: (error:NSError?)->()){
        //TODO:获取用户信息
        TZNetWorkTool.shardNetWorkTool.loadAccountInfo { (result, error) -> () in
            if result == nil || error != nil{
                //错误
                finished(error: error)
                return
            }
            //没有错误,存储用户信息
            self.avatar_large = result!["avatar_large"] as? String
            self.screen_name = result!["screen_name"] as? String
            self.saveAccountInfo()
            //将最新的模型赋值给 TZUserAccount.accountInfo
            TZUserAccount.accountInfo = self
            //调用闭包通知控制器获取用户信息成功
            finished(error: nil)
        }
        
    }
}